package org.springframework.boot.netty.viewResolver;

import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.netty.NettyProperties;
import org.springframework.boot.netty.support.ModelAndView;
import org.springframework.boot.netty.view.ThymeleafView;
import org.springframework.boot.netty.view.View;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.util.ResourceUtils;

import java.io.File;

/**
 * Author: huoxingzhi
 * Date: 2020/12/28
 * Email: hxz_798561819@163.com
 */
@Order(1)
public class ThymeleafViewResolver implements ViewResolver {

    private NettyProperties nettyProperties;
    private ApplicationContext applicationContext;


    @Override
    public View resolveViewName(ModelAndView modelAndView) throws Exception {
        String viewName = this.nettyProperties.getViewPrefix()+
                File.separator +
                modelAndView.getView()+
                ".html";
        File viewFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+viewName.trim());
        if(viewFile.exists()){
            return this.applicationContext.getBean(ThymeleafView.class);
        }
        return null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;

        this.nettyProperties = applicationContext.getBean(NettyProperties.class);
    }
}
